package com.maxjay.system.web.listener;

import java.io.FileInputStream;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.maxjay.component.metadata.core.EntityContext;
import com.maxjay.system.constant.SystemParamKeys;
import com.maxjay.system.core.Application;
import com.maxjay.system.core.cache.BufferedDictTablePool;
import com.maxjay.system.core.cache.SystemDataHolder;
import com.maxjay.system.core.spring.SpringBeanContext;

public class SystemInitListener implements ServletContextListener {

	/** 日志记录器 */
	private static Logger logger = Logger.getLogger(SystemInitListener.class);
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		// TODO: 如果有线程，需要在此销毁
		Application.destroy();
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		logger.info("Spring初始化开始...");
		SpringBeanContext beanContext = new SpringBeanContext(event.getServletContext());
		EntityContext entityContext = new EntityContext(beanContext);
		Application.setBeanContext(beanContext);
		Application.setEntityContext(entityContext);
		logger.info("Spring初始化[OK]");
		BufferedDictTablePool.init();
		otherInit(event);
	}

	public void otherInit(ServletContextEvent event) {
		System.setProperty(SystemParamKeys.WEBCONTEXT_ROOT_PATH, event.getServletContext().getRealPath("/"));
		SystemDataHolder.init();
		configLog4jPath(event);
	}
	
	private void configLog4jPath(ServletContextEvent event) {
		String webRootPath=event.getServletContext().getRealPath("/");
		String logConfigFile = event.getServletContext().getInitParameter("log4jConfFile");;
		String logFilePath="/log/";
		if(logConfigFile!=null) {
			Properties prop = new Properties(); 
			try{
				prop.load(new FileInputStream(webRootPath+logConfigFile)); //加载log4j.properties
				prop.setProperty("log4j.appender.R.File", webRootPath + logFilePath + prop.getProperty("log4j.appender.R.File")); //设置日志文件的输出路径
				PropertyConfigurator.configure(prop); //加载配置项
			} catch(Exception e) {
				logger.error("初始化log4j日志输出路径异常，异常信息："+e.getMessage(), e);
			}
		}
	}
}
